﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Web;
using System.Xml.Linq;
using FaceSharp.Api.GraphApi;
using FaceSharp.Api.RestApi;

namespace FaceSharp.Api.Objects
{
    public class Application : GraphBase
    {
        private readonly User _user;
        private readonly RestBase _restBase;
        private readonly IFacebookCore _facebookCore;

        public Application(IFacebookCore facebookCore)
            : base(facebookCore)
        {
            _facebookCore = facebookCore;
            _restBase = new RestBase(facebookCore);
            _user = new User(facebookCore);
        }

        public IEnumerable<Types.Application> GetCurrentUsersApps()
        {
            Trace.Write("Begin Request", "Facebook.Objects.Application.GetCurrentUsersApps");
            string results = null;
            var queryResults = _restBase.ExecuteFql("SELECT application_id, role FROM developer WHERE developer_id = " + _user.GetCurrentUserId().ToString());

            var applications = new List<Types.Application>();
            if (!String.IsNullOrEmpty(queryResults))
            {
                XNamespace ns = "http://api.facebook.com/1.0/";
                var xdoc = XDocument.Parse(queryResults);
                var appIds = from app in xdoc.Descendants(ns + "developer")
                             select (string)app.Element(ns + "application_id");
                var jObject = MakeGraphRequest(appIds);

                if (jObject != null)
                {
                    applications.AddRange(
                        appIds.Select(appId => jObject[appId]).Where(x => x != null).Select(
                        application => new Types.Application()
                        {
                            Id = long.Parse((string)application["id"]),
                            Name = (string)application["name"],
                            Description = (string)(application["description"] ?? ""),
                            Link = (string)application["link"]
                        }));
                }

            }
            Trace.Write("End Request", "Facebook.Objects.Application.GetCurrentUsersApps");
            return applications.AsEnumerable();
        }

        public string GetApplicationAccessToken()
        {
            return GetApplicationAccessToken(_facebookCore.ApplicationId, _facebookCore.ApplicationSecret);
        }

        public string GetApplicationAccessToken(string applicationId, string applicationSecret)
        {
            string results = null;
            var client = new RestSharp.RestClient("https://graph.facebook.com");
            var request = new RestSharp.RestRequest("/oauth/access_token", RestSharp.Method.POST);
            
            request.AddParameter("type", "client_cred");
            request.AddParameter("client_id", applicationId);
            request.AddParameter("client_secret", applicationSecret);

            var response = client.Execute(request);
            if (response.StatusCode == HttpStatusCode.OK)
            {
                results = System.Web.HttpUtility.ParseQueryString(response.Content).Get("access_token");
            }
            else
            {
                Trace.TraceWarning("Status Code: " + response.StatusCode + " Content: " + response.Content + " Headers : " + response.Headers);
            }
            return results;
        }
    }
}